<!-- 业务详情 -->
<template>
  <div class="overview-detail">
    <div :breadcrumb="{ props: { routes, itemRender } }" @back="() => this.$router.go(-1)">
      <a-card :bordered="false">
        <!-- 操作按钮 end -->
        <!-- <a-descriptions title="项目管理" style="padding-top: 20px"></a-descriptions> -->
        <!-- tab切换 start -->
        <a-tabs v-model="activedKey" style="margin-bottom: 20px" @change="callback">
          <a-tab-pane :tab="$t('all.autotext374')" :key="1">
            <Role :editable="editable"></Role>
          </a-tab-pane>
          <a-tab-pane :tab="$t('all.autotext949')" :key="2">
            <!-- 项目成员 -->
            <Members @cancelMember="cancelMember" :editable="editable" />
          </a-tab-pane>
          <!-- 受试者 -->
          <!-- <a-tab-pane tab="受试者" :key="2" v-if="$auth('PROJECT.PROJECT_PATIENT')">
            <keep-alive>
              <Subject :datailId="parseInt($route.query.id)" />
            </keep-alive>
          </a-tab-pane> -->
          <!-- 访视管理 -->
          <a-tab-pane :tab="$t('all.autotext231')" :key="3">
            <keep-alive>
              <Visit :editable="editable" />
            </keep-alive>
          </a-tab-pane>
          <!-- 审批流程 -->
          <a-tab-pane :tab="$t('all.autotext1286')" :key="4">
            <keep-alive>
              <Approval :editable="editable" :research="researchApprovalInfo" :subject="subjectApprovalInfo"
                        @update="initApproval"
              />
            </keep-alive>
          </a-tab-pane>
          <!-- 费用科目 -->
          <a-tab-pane :tab="$t('all.autotext1507')" :key="5">
            <keep-alive>
              <Expense :editable="editable" />
            </keep-alive>
          </a-tab-pane>
          <!-- 项目合同 -->
          <a-tab-pane :tab="$t('all.autotext1257')" :key="6">
            <keep-alive>
              <Contract :editable="editable" />
            </keep-alive>
          </a-tab-pane>
          <a-tab-pane tab="用户协议" :key="7">
            <Agreement />
          </a-tab-pane>
          <!-- 项目费用 -->
          <!-- <a-tab-pane tab="项目费用" v-if="$auth('PROJECT.PROJECT_COST')" :key="7">
            <keep-alive>
              <Bill :detailsInfo="detailsInfo" :datailId="parseInt($route.query.id)" />
            </keep-alive>
          </a-tab-pane> -->
        </a-tabs>
        <!-- tab切换 end -->
      </a-card>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { getProjectDetail, getProjectDelete, getProjectUpdate } from '@/api/overview/contract'
import { getApprovalDetail } from '@/api/overview/approval'
import { deleteLeader } from '@/api/overview/member'
import Members from './components/members'
// import Subject from './components/subject'
import Contract from './components/contract'
// import Bill from './components/bill'
import Visit from './components/visit.vue'
import Approval from './components/approval'
import Expense from './components/expense'
import { getUnread } from '@/api/system/message'
import { mapState } from 'vuex'
import Role from './components/role'
import Agreement from './components/agreement'


export default {
  components: {
    Members,
    // Subject,
    Contract,
    // Bill,
    Visit,
    Approval,
    Expense,
    Role,
    Agreement
  },
  provide () {
    return {
      detailsInfoFn: () => this.detailsInfo
    }
  },
  data () {
    const defaultItemRender = ({ route, params, routes, paths, h }) => {
      return routes.indexOf(route) === routes.length - 1 && (
        <span>{route.breadcrumbName}</span>) || (
        <router-link to={{ path: route.path || '/', params }}>{route.breadcrumbName}</router-link>
      )
    }
    return {
      columns: [
        {
          title: 'ID',
          key: 'id',
          dataIndex: 'id'
        },
        {
          title: this.$t('all.autotext1150'),
          key: 'ptsNo',
          dataIndex: 'ptsNo'
        },
        {
          title: this.$t('all.autotext550'),
          key: 'applyReason',
          dataIndex: 'applyReason'
        },
        {
          title: this.$t('all.autotext867'),
          key: 'totalAmount',
          dataIndex: 'totalAmount'
        },
        {
          title: this.$t('all.autotext244'),
          key: 'createTime',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: this.$t('all.autotext1466'),
          key: 'status',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      detailsInfo: {}, // 详情列表
      activedKey: 1,
      projectId: null,
      modalVisible: false,
      dynamicTitle: '',
      editVisible: false,
      editContent: {},
      researchApprovalInfo: {}, // 研究者审批流
      subjectApprovalInfo: {}, // 受试者审批流
      removeLoading: false,
      pId: null, // 项目id 从store中获取的代替从路由中获取
      // 自定义面包屑
      routes: [{
        path: '',
        breadcrumbName: this.$t('all.autotext821')
      }, {
        path: '/overview/config',
        breadcrumbName: this.$t('all.autotext905')
      }, {
        path: '/overview/config/detail',
        breadcrumbName: this.$t('all.autotext1482')
      }],
      itemRender: defaultItemRender,
      editable: false // 编辑权限
    }
  },
  computed: {
    ...mapState({
      appActiveKey: state => state.app.activeKey
    }),
    isYWAdmin () {
      return this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.YW_ADMIN.value)
    }
  },
  created () {
    const pro = localStorage.getItem('CURRENT_PROID')
    if (pro) {
      this.pId = parseInt(pro)
      this.$route.query.id = this.pId
    }
    if (this.$route.query.id) {
      this.pId = this.$route.query.id
    }

    this.editable = this.$route.query.type === 'edit'

    getUnread({ proId: this.pId }).then(res => {
      this.$globalVue.$emit('unReadMsgCount', res)
    })
  },
  mounted () {
    this.detailsList()
    this.initTabs()
    this.initApproval()
  },
  methods: {
    // 获取审批流详情
    async initApproval () {
      this.researchApprovalInfo = await getApprovalDetail({
        proId: this.pId,
        type: 1
      })
      this.subjectApprovalInfo = await getApprovalDetail({
        proId: this.pId,
        type: 2
      })
    },
    // 根据权限初始化项目管理的tabs
    initTabs () {
      const arr = [
        this.$auth('PROJECT.PROJECT_MEMBER'),
        this.$auth('PROJECT.PROJECT_PATIENT'),
        this.$auth('PROJECT.PROJECT_VISIT'),
        this.$auth('PROJECT.PROJECT_REVIEW'),
        this.$auth('PROJECT.PROJECT_EXPENSE'),
        this.$auth('PROJECT.PROJECT_AGREEMENT'),
        this.$auth('PROJECT.PROJECT_COST')
      ]
      this.activedKey = this.appActiveKey ? this.appActiveKey : arr.findIndex(Boolean) + 1
    },
    detailsList () {
      const datailsId = this.$route.query.id
      if (datailsId) {
        getProjectDetail({
          id: Number.parseFloat(datailsId)
        }).then(res => {
          this.detailsInfo = res
          const { protocolNo, name, status, stage, budget, no, contractNo, buildTime, createrId, businessName, serviceCharge, serviceChargePercent } = res
          const sponsorIds = res.sponsorIds.split(',').map(Number) // 注：后端返回的是个字符串需将其转为数组(split分割后是个string数组，map方法将其转为number数组)
          this.editContent = { protocolNo, name, sponsorIds, status, stage, budget, no, contractNo, buildTime, createrId, businessName, serviceCharge, serviceChargePercent }
          this.editContent.buildTime = moment(this.editContent.buildTime).format('YYYY-MM-DD')
        })
      }
    },
    callback (key) {
      this.$store.commit('changeActiveKey', key)
    },
    // 邀请项目负责人
    inviteResponderAdd () {
      this.modalVisible = true
      this.projectId = this.$route.query.id
      this.$refs.addMemberRef.getNewRolesList()
    },
    // 点击删除项目
    deleteProject () {
      getProjectDelete({
        id: this.$route.query.id,
        status: this.detailsInfo.status
      }).then(res => {
        this.$message.success(this.$t('all.autotext1455'))
        this.$router.push({ name: 'All' })
      })
    },
    // 判断状态是否可删除
    handleVisibleChange () {
      if (this.detailsInfo.status === 2) {
        this.dynamicTitle = this.$t('all.autotext1481')
      } else {
        this.dynamicTitle = this.$t('all.autotext1234')
      }
    },
    // 点击修改信息
    clickEditMessage () {
      this.editVisible = true
    },
    // 提交修改
    updateEdit (e) {
      delete e.buildTime
      delete e.businessName
      getProjectUpdate({
        ...e,
        id: this.$route.query.id
      })
        .then(res => {
          if (res.message) {
            this.$message.warning(res.message)
          } else {
            this.$message.success(this.$t('all.autotext1108'))
          }
          this.editVisible = false
          this.detailsList()
        })
    },
    cancelMember () {
      this.detailsList()
    },
    deletePm () {
      this.removeLoading = true
      deleteLeader({ id: this.detailsInfo.teamId }).then(res => {
        this.removeLoading = false
        this.detailsList()
        this.$message.success(this.$t('all.autotext470'))
      }).catch(_ => {
        this.removeLoading = false
      })
    },
    invitCb () {
      this.detailsList()
      if (this.activedKey === 1) {
        this.activedKey = 0
        setTimeout(() => {
          this.activedKey = 1
        }, 200)
      }
    }
  }
}
</script>
<style scoped lang="scss"></style>
